
<?php
if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Posts extends CI_Controller {

    var $Array_Data;
    
    public function __construct() {
        parent::__construct();
        if(update_user() != 2){
            redirect(site_url() . '/welcome/not_authorized');
        };   
        $this->Array_Data['UserInfo'] = $this->session->userdata('UserInfo');
    }
    
    public function Index() {
        if ($this->Array_Data['UserInfo']['UserType'] == 'hire') {
            $CI = &get_instance();
            $CI->load->model('Posts_model', 'Post');
            $CI->load->model('Category_model', 'Category');
            $Array_Data['UserInfo'] = $this->session->userdata('UserInfo');
            /*----- Page Caculate ----*/
            if(isset($_GET['Page']))
                $Current_Page = $_GET['Page'];
            else
                $Current_Page = 1;
            $offset = ($Current_Page-1) * 10;
            
            $Array_Data['TotalNum'] = $CI->Post->Get_Num(
                    array('RelUserEmail'    => $Array_Data['UserInfo']['UserEmail'],
                        'PostStatus'        => 1));
            
            //Caculate Limit
            $limit = $Array_Data['TotalNum'] - (($Current_Page-1)*10);
            $limit = ($limit>=10)?10:$limit;
            /*---- End of Page Caculate ----*/
            
            /* ----- Get Posts ----- */
            $TempUserPosts = $CI->Post->Get_Advanced("*",array(
                'RelUserEmail'  => $Array_Data['UserInfo']['UserEmail'],
                'PostStatus'    => 1), 
                    "PostDate desc", $limit, $offset);
            $UserPosts = array();
            foreach($TempUserPosts as $Post){
                $CategoryName = $CI->Category->Get(array('CategoryID' => $Post['Field']));
                $Post['CategoryName'] = $CategoryName[0]['CategoryName'];
                $UserPosts[] = $Post;
            }
            
            $Array_Data['UserPosts'] = $UserPosts;
            $Array_Data['Current_Page'] = $Current_Page;
            /* ----- End of get Post ----- */ 
            $this->load->view('user_group2/posts/index_view', $Array_Data);
        } else {
            redirect(site_url() . '/welcome/not_authorized');
        }
    }
    
    public function disable(){
        if ($this->Array_Data['UserInfo']['UserType'] == 'hire') {
            $CI = &get_instance();
            $CI->load->model('Posts_model', 'Post');
            $CI->load->model('Category_model', 'Category');
            $Array_Data['UserInfo'] = $this->session->userdata('UserInfo');
            /*----- Page Caculate ----*/
            if(isset($_GET['Page']))
                $Current_Page = $_GET['Page'];
            else
                $Current_Page = 1;
            $offset = ($Current_Page-1) * 10;
            
            $Array_Data['TotalNum'] = $CI->Post->Get_Num(
                    array('RelUserEmail'    => $Array_Data['UserInfo']['UserEmail'],
                        'PostStatus'        => 0));
            
            //Caculate Limit
            $limit = $Array_Data['TotalNum'] - (($Current_Page-1)*10);
            $limit = ($limit>=10)?10:$limit;
            /*---- End of Page Caculate ----*/
            
            /* ----- Get Posts ----- */
            $TempUserPosts = $CI->Post->Get_Advanced("*",array(
                'RelUserEmail'  => $Array_Data['UserInfo']['UserEmail'],
                'PostStatus'    => 0), 
                    "PostDate desc", $limit, $offset);
            $UserPosts = array();
            foreach($TempUserPosts as $Post){
                $CategoryName = $CI->Category->Get(array('CategoryID' => $Post['Field']));
                $Post['CategoryName'] = $CategoryName[0]['CategoryName'];
                $UserPosts[] = $Post;
            }
            
            $Array_Data['UserPosts'] = $UserPosts;
            $Array_Data['Current_Page'] = $Current_Page;
            /* ----- End of get Post ----- */ 
            $this->load->view('user_group2/posts/disable_posts_view', $Array_Data);
        } else {
            redirect(site_url() . '/welcome/not_authorized');
        }
    }

    public function Create() {
;
        $UserInfo = $this->session->userdata('UserInfo');
        $PictureURL = $_POST['PictureURL'];
        $Field = $_POST['child-field'];
        $Content = $_POST['content'];
        $Subject = $_POST['subject'];
        $Requirement = $_POST['MainRequirement'] . "##";
        if (isset($_POST['RequirementTitle'])) {
            $_POST['RequirementCondition'][count($_POST['RequirementTitle'])] = "";
            for ($i = 0; $i < count($_POST['RequirementTitle']); $i++) {
                $tempString = $_POST['RequirementTitle'][$i] . "@@"
                            . $_POST['RequirementLevel'][$i] . "";
                if ($tempString != "@@") {
                    $Requirement .= $tempString . $_POST['RequirementCondition'][$i];
                }
            }
        }
        $Contact = $_POST['contact-id'] . "@@" . $_POST['contact-content'];
        $Workplace = $_POST['workplaces-id'] . "@@"
                    . $_POST['workplaces-content'] . "@@";
        $NumApplicant = $_POST['num-applicant'];
        $Salary = $_POST['salary'];
        $DateEnd = $_POST['DateEnd'];
        $date = date('Y-m-d H:i:s');

        $data = array(
            'RelUserEmail'          => $UserInfo['UserEmail'],
            'Subject'               => $Subject,
            'Content'               => $Content,
            'MinimumRequirement'    => $Requirement,
            'Field'                 => $Field,
            'ContactContent'        => $Contact,
            'AddressWorkPlaces'     => $Workplace,
            'PictureURL'            => $PictureURL,
            'PostDate'              => $date,
            'PostStatus'            => True,
            'NumApplicant'          => $NumApplicant,
            'Salary'                => $Salary,
            'DateEnd'               => $DateEnd
        );
        $CI = &get_instance();
        $CI->load->model('Posts_model', 'Post');
        $CI->Post->Insert($data);
        
        redirect(site_url().'/user_group2/posts');
    }

    public function Upload_Picture() {
        $ext = pathinfo($_FILES['avatar']['name'], PATHINFO_EXTENSION);
        $UserInfo = $this->session->userdata('UserInfo');
        $file_name = md5($UserInfo['UserEmail']) . '.' . $ext;
        $target_path = image_url(true) . $file_name;

        if (@move_uploaded_file($_FILES['avatar']['tmp_name'], $target_path)) {
            $result = $file_name;
        }
        echo '<script language="javascript" type="text/javascript">window.top.window.StopUpload("' . $result . '");</script>';
    }
    
    public function post_create_page(){
        $CI =& get_instance();
        $CI->load->model("Users2_model","Users2");
        $CI->load->model("Category_model","Category");
        $this->Array_Data['Category'] = $CI->Category->GetAllCategory();
        $this->Array_Data['UserInfo']['Contact'] = $CI->Users2->GetAddressArray($this->Array_Data['UserInfo']['UserEmail']);
        $this->load->view('user_group2/posts/create',$this->Array_Data);
    }
    
    public function Show($ID){    
        $CI =& get_instance();    
        $CI->load->model('Posts_model', 'Post');
        $Post = $CI->Post->Get(array('PostID'   =>  $ID));
        $this->Array_Data['Post'] = $Post[0];
        $this->load->view('user_group2/posts/manage_post_view', $this->Array_Data);
        
    }
    
    public function manage_post_content($ID){
        $CI =& get_instance(); 
        $CI->load->helper('string_addition');
        $CI->load->model('Posts_model',     'Post');
        $CI->load->model("Users2_model",    "Users2");
        $CI->load->model("Category_model",  "Category");
        $Post = $CI->Post->Get(array('PostID'   =>  $ID));
        $Post = $Post[0];
        $Post['Category'] = $CI->Category->Get(array('CategoryID'   =>  $Post['Field']));
        $Post['Category'] = $Post['Category'][0];
        $TotalRequirement = explode('##',$Post['MinimumRequirement']);
        $Post['MinimumRequirement']                 = array();
        $Post['MinimumRequirement']['EduLevReq']    = $TotalRequirement[0];
        if($TotalRequirement[1])
            $Post['MinimumRequirement']['OptReqs']      = ConvtAddQual($TotalRequirement[1],false);
        $Post['ContactID'] = explode("@@", $Post['ContactContent']);
        $Post['ContactID'] = $Post['ContactContent'][0];
        $Post['AddrID'] = explode("@@", $Post['AddressWorkPlaces']);
        $Post['AddrID'] = $Post['AddressWorkPlaces'][0];
        $this->Array_Data['Post'] = $Post;
        $this->Array_Data['Category'] = $CI->Category->GetAllCategory();
        $this->Array_Data['UserInfo']['Contact'] = $CI->Users2->GetAddressArray($this->Array_Data['UserInfo']['UserEmail']);
        $this->load->view('user_group2/posts/post_management/post_content_management', $this->Array_Data);
    }
    
    public function manage_post_applicants($ID,$Type='Pending'){
        $CI =& get_instance(); 
        $CI->load->helper('string_addition');
        $CI->load->model('Posts_model',         'Post');
        $CI->load->model('Post_Applies_model',  'PA');
        $CI->load->model('Users2_PostReceiveApplicants_model',  'PRA');
        $CI->load->model('Users3_model',        'Us3');
        $Post = $CI->Post->Get(array('PostID'   =>  $ID));
        $Post = $Post[0];
        
        //Retrieve Applicants
        $Post_Applies   = $CI->PA->Get_Advanced('*',array('RelPostID' => $Post['PostID']),'ApplyDate desc');
        $Applicants = array();
        foreach($Post_Applies as $Post_Apply){
            //Check if already accepted
            $temp = $CI->PRA->Get(array('RelPostApplyID' => $Post_Apply['PostApplyID']));
            if($Type=='Pending')
                if(count($temp) != 0) continue;
            if($Type=='Accept')
                if(count($temp) == 0) continue;
            
            $Applicant = $CI->Us3->Get_Advanced('UserGroup3ID, RelUserEmail, UserFullname, AvatarLink'
                    ,array('RelUserEmail' =>  $Post_Apply['RelUserEmailGroup3']));
            $Applicant      = $Applicant[0];
            $Applicants[]   = array_merge($Applicant,$Post_Apply);
        }
        if($Type=='Pending')
            $Date_Applies = $CI->PA->Get_Day_Applies(array('RelPostID' => $ID));
        if($Type=='Accept')
            $Date_Applies = $CI->PRA->Get_Day_Receives(array('RelPostID' => $ID));
        
        $this->Array_Data['Post']                   = $Post;
        $this->Array_Data['Post']['Applicants']     = $Applicants;
        $this->Array_Data['Post']['Date_Applies']   = $Date_Applies;
        $this->Array_Data['Type']                   = $Type;
        $this->load->view('user_group2/posts/post_management/post_applicants_management', $this->Array_Data);
    }
    public function edit_post(){
        $UserInfo       = $this->Array_Data['UserInfo'];
        $PictureURL     = $_POST['PictureURL'];
        $Field          = $_POST['child-field'];
        $Content        = $_POST['content'];
        $Subject        = $_POST['subject'];
        $Requirement    = $_POST['MainRequirement'] . "##";
        if (isset($_POST['RequirementTitle'])) {
            $_POST['RequirementCondition'][count($_POST['RequirementTitle'])] = "";
            for ($i = 0; $i < count($_POST['RequirementTitle']); $i++) {
                $tempString = $_POST['RequirementTitle'][$i] . "@@"
                            . $_POST['RequirementLevel'][$i] . "";
                if ($tempString != "@@") {
                    $Requirement .= $tempString . $_POST['RequirementCondition'][$i];
                }
            }
        }

        $Contact        = $_POST['contact-id'] . "@@" . $_POST['contact-content'];
        $Workplace      = $_POST['workplaces-id'] . "@@"
                    . $_POST['workplaces-content'] . "@@";
        $NumApplicant   = $_POST['num-applicant'];
        $Salary = $_POST['salary'];
        $DateEnd        = $_POST['DateEnd'];
        $data = array(
            'RelUserEmail'          => $UserInfo['UserEmail'],
            'Subject'               => $Subject,
            'Content'               => $Content,
            'MinimumRequirement'    => $Requirement,
            'Field'                 => $Field,
            'ContactContent'        => $Contact,
            'AddressWorkPlaces'     => $Workplace,
            'PictureURL'            => $PictureURL,
            'NumApplicant'          => $NumApplicant,
            'Salary'                => $Salary, 
            'DateEnd'               => $DateEnd
        );
        $CI = &get_instance();
        $CI->load->model('Posts_model', 'Post');
        $CI->Post->Update($data,array('PostID'  =>  $_POST['PostID']));
        redirect(site_url().'/user_group2/posts/'.$_POST['PostID']);
    }
    
    public function apply_show($PostID, $UserGroup3ID){
        $CI = &get_instance();
        $CI->load->helper('string_addition');
        $CI->load->model('Posts_model', 'Post');
        $CI->load->model("Users3_model","Users3");
        $CI->load->model('Post_Applies_model', 'PA');
        $CI->load->model('Users3_Activities_model','Us3Act');
        $CI->load->model('Users3_Qualification_model','Users3Qual');
        $CI->load->model('Users3_WorkedPlaces_model','Exp');
        $DesInfo                    = $CI->Users3->GetInformation(array('UserGroup3ID' => $UserGroup3ID));
        $DesInfo                    = $DesInfo[0];
        $DesInfo['Qualifications']  = $CI->Users3Qual->Get(array(
            'RelUserEmail'  => $DesInfo['RelUserEmail']
        ));
        $DesInfo['WorkedPlaces']    = $CI->Exp->Get_Advanced("*",
            array('RelUserEmail'  => $DesInfo['RelUserEmail']),
            'Year desc'
        );
        
        $DesInfo['Activities']                 = $CI->Us3Act->Get_Advanced("*",
                array('RelUserID'   =>  $DesInfo['UserGroup3ID']),
                "ActYear ASC"
                );
        
        $Post       = $CI->Post->Get(array('PostID'     =>      $PostID));
        $Post       = $Post[0];
        
        $Post_App   = $CI->PA->Get(array('RelPostID'   =>  $PostID));
        $Post_App   = $Post_App[0];
        
        $Post_App   = array_merge($Post_App, $Post);
        
        $this->Array_Data['PA']         =   $Post_App;
        $this->Array_Data['DesInfo']    =   $DesInfo;
        
        $PostRequirement = explode('##',$Post['MinimumRequirement']);
        $PostRequirement = $PostRequirement[1];
        $PostRequirement = ConvtAddQual($PostRequirement, false);
        $this->Array_Data['PAReqs'] = compare_requirement($DesInfo['Qualifications'], $PostRequirement);
        
        $this->load->view('user_group2/posts/post_applies_view'
                ,$this->Array_Data);
    }
    
    public function accept_applicants(){
        error_reporting(0);
        @ini_set('display_errors', 0);
        //Add Post Receive
        $CI = &get_instance();
        $CI->load->model('Users2_PostReceiveApplicants_model',  'PRA');
        $CI->load->model('Post_Applies_model',                'PA');
        $CI->load->model('Users3_Notification_model',           'Us3Noti');
        $ListID = $_POST['ListID'];
        foreach($ListID as $ID){

            //Add Notification
            //Get Post_Applies
            $PA = $this->PA->Get(array('PostApplyID'    =>  $ID));
            $PA = $PA[0];
            
            $data = array(
                'RelUserEmail'  =>  $PA['RelUserEmailGroup3'],
                'RelPostID'     =>  $PA['RelPostID'],
                'Content'       =>  'You have been accepted to <b>'.'#POSTNAME#'.'</b>',
                'Type'          =>  'Accept',
            );
            
            $CI->PRA->Insert(array(
                'RelPostApplyID'    =>  $ID,
                'Content'           =>  $_POST['Content'],
                'RelPostID'         =>  $PA['RelPostID'],
            ));
            $CI->Us3Noti->Insert($data);
            $max_id = $CI->Us3Noti->Get_Max();
            $CI->Us3Noti->Update(
                array('LinkTo'  =>  'user_group3/notification/' . $max_id . '?Additional[]=' . $PA['RelPostID']), 
                array('NotiID'  => $max_id));
        }
        echo "1";
    }
    
    public function disable_posts(){
        $ListID         = $_POST['ListID'];
        $UserInfo       = $this->Array_Data['UserInfo'];
        $CI =& get_instance();
        $CI->load->model('Posts_model',                 'Posts');
        $CI->load->model('Users3_Notification_model',   'Us3Noti');
        $CI->load->model('Post_Applies_model',          'PA');
        foreach($ListID as $ID){
            $CI->Posts->Update(array("PostStatus" => 0), 
                    array('PostID'    =>  $ID));
        }
        
        echo "1";
    }
    
    public function enable_posts(){
        $ListID         = $_POST['ListID'];
        $UserInfo       = $this->Array_Data['UserInfo'];
        $CI =& get_instance();
        $CI->load->model('Posts_model',                 'Posts');
        $CI->load->model('Users3_Notification_model',   'Us3Noti');
        $CI->load->model('Post_Applies_model',          'PA');
        foreach($ListID as $ID){
            $CI->Posts->Update(array("PostStatus" => 1), 
                    array('PostID'    =>  $ID));
        }
        
        echo "1";
    }
}
